package http

import (
	"context"
	"errors"
	"flare-admin/config/common"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

//var (
//	Svc *service.Service
//)

type FlareHttpServerConfig struct {
	Host string
	Port int
	Mode string
}

func NewFlareHttpServerConfigFromGlobalConfig(config *common.Config) *FlareHttpServerConfig {
	return &FlareHttpServerConfig{
		Host: config.Server.Host,
		Port: config.Server.Port,
		Mode: config.Mode,
	}
}

type FlareHttpServer struct {
	engine       *gin.Engine
	ServerConfig *FlareHttpServerConfig
}

func NewFlareHttpServer(config *common.Config) (*FlareHttpServer, error) {
	server := gin.New()
	server.Use(gin.Recovery())
	server.Use(Cors())

	flareHttpServer := &FlareHttpServer{
		engine:       server,
		ServerConfig: NewFlareHttpServerConfigFromGlobalConfig(config),
	}
	err := flareHttpServer.RegisterRoute()
	if err != nil {
		logrus.Errorf("[NewFlareHttpServer] - [New] - failed to register route: %v", err)
		return nil, err
	}
	return flareHttpServer, nil
}

// Run 阻塞现成直到接收到signal
func (s *FlareHttpServer) Run() error {
	addr := fmt.Sprintf("%s:%d", s.ServerConfig.Host, s.ServerConfig.Port)
	srv := &http.Server{
		Addr:    addr,
		Handler: s.engine,
	}
	//Svc = service.Svc
	go func() {
		if err := srv.ListenAndServe(); err != nil {
			if !errors.Is(err, http.ErrServerClosed) {
				logrus.Fatal("[FlareHttpServer] - [Run] - failed to start server: ", err)
			}
		}
	}()

	stopCh := make(chan os.Signal)
	signal.Notify(stopCh, syscall.SIGINT, syscall.SIGTERM)
	<-stopCh

	// gracefully shutdown
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		logrus.Fatal("[FlareHttpServer] - [Run] - failed to shutdown server: ", err)
	}
	logrus.Infof("[FlareHttpServer] - [Run] - server shutdown gracefully")
	return nil
}

func Cors() gin.HandlerFunc {
	c := cors.Config{
		AllowOrigins: []string{"http://127.0.0.1:5173", "http://localhost:5173", "http://10.176.40.186:5173"},
		// AllowOrigins: []string{"http://127.0.0.1:8800", "http://localhost:8800", "http://10.176.40.186:8800"},
		// AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Content-Type", "Authorization"},
		ExposeHeaders:    []string{"Content-Length", "Authorization"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}
	return cors.New(c)
}
